package com.itboye.sunsun.application;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.utils.DebugToast;
import com.itboye.sunsun.utils.SPUtils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.widget.Toast;
/**
 * 崩溃日志收集
 * @author Young
 *
 */
public class MyUnCatchExceptionHandler implements UncaughtExceptionHandler{

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		ex.printStackTrace();
//		App.ctx.activitys;
		//将一些信息保存到SDcard中  
		if (Looper.myLooper()!=Looper.getMainLooper()) {
			  savaInfoToSD(App.ctx, ex);  
	          
		        //提示用户程序即将退出  
//		        DebugToast.show(  "Error! \n请把文件管理器中的SunSunCrash文件发给安卓攻城狮！",1);  
		     //   showToast(App.ctx, "SunSun崩溃了→_→\n请结束‘森森休闲’，并尝试再次启动");  
//		        try {  
//		            thread.sleep(2000);  
//		        } catch (InterruptedException e) {  
//		           
//		        }  
		        App.ctx.exit();
		}
      
//      android.os.Process.killProcess(android.os.Process.myPid());    
//        System.exit(1);  
          
        //完美退出程序方法  
    //    ExitAppUtils.getInstance().exit();  
          
    }  
  
      
   
    /** 
     * 显示提示信息，需要在线程中显示Toast 
     * @param context 
     * @param msg 
     */  
    private void showToast(final Context context, final String msg){  
        new Thread(new Runnable() {  
              
            @Override  
            public void run() {  
                Looper.prepare();  
                Toast.makeText(context, msg, 2).show(  ) ;  
                Looper.loop();  
            }  
        }).start();  
    }  
      
      
    /** 
     * 获取一些简单的信息,软件版本，手机版本，型号等信息存放在HashMap中 
     * @param context 
     * @return 
     */  
    private Map<String, String> obtainSimpleInfo(Context context){  
        Map<String, String> map = new ArrayMap<String, String>();  
        PackageManager mPackageManager = context.getPackageManager();  
        PackageInfo mPackageInfo = null;  
        try {  
            mPackageInfo = mPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);  
        } catch (NameNotFoundException e) {  
            e.printStackTrace();  
        }  
          
        map.put("time", paserTime(System.currentTimeMillis()));
        map.put("versionName", mPackageInfo.versionName);  
        map.put("versionCode", "" + mPackageInfo.versionCode);  
          
        map.put("MODEL", "" + Build.MODEL);  
        map.put("SDK_INT", "" + Build.VERSION.SDK_INT);  
        map.put("PRODUCT", "" +  Build.PRODUCT);  
        map.put("RELEASE_NAME", "" +Build.VERSION.RELEASE);  
        map.put("CPU", "" +Build.CPU_ABI);  
        map.put("uid", (String)SPUtils.get(context, null, SPContants.USER_ID	, ""));
        return map;  
    }  
      
      
    /** 
     * 获取系统未捕捉的错误信息 
     * @param throwable 
     * @return 
     */  
    private String obtainExceptionInfo(Throwable throwable) {  
        StringWriter mStringWriter = new StringWriter();  
        PrintWriter mPrintWriter = new PrintWriter(mStringWriter);  
        throwable.printStackTrace(mPrintWriter);  
        mPrintWriter.close();  
          
        Log.v("TAG", mStringWriter.toString());  
        return mStringWriter.toString();  
    }  
      
    /** 
     * 保存获取的 软件信息，设备信息和出错信息保存在SDcard中 
     * @param context 
     * @param ex 
     * @return 
     */  
    private String savaInfoToSD(Context context, Throwable ex){  
        String fileName = null;  
        StringBuffer sb = new StringBuffer();  
          
        for (Map.Entry<String, String> entry : obtainSimpleInfo(context).entrySet()) {  
            String key = entry.getKey();  
            String value = entry.getValue();  
            sb.append(key).append(" = ").append(value).append("\n");  
        }    
          
        sb.append(obtainExceptionInfo(ex));  
          
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
          
              
            try{  
            	  File dir = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + File.separator + "SunSunCrash" + File.separator);  
                  if(! dir.exists()){  
                      dir.mkdir();  
                  }  
                fileName = dir.toString() + File.separator + paserTime(System.currentTimeMillis()) + ".log";  
                FileOutputStream fos = new FileOutputStream(fileName);  
                fos.write(sb.toString().getBytes());  
                fos.flush();  
                fos.close();  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
              
        }  
          
        return fileName;  
          
    }  
      
      
    /** 
     * 将毫秒数转换成yyyy-MM-dd-HH-mm-ss的格式 
     * @param milliseconds 
     * @return 
     */  
    private String paserTime(long milliseconds) {  
        System.setProperty("user.timezone", "Asia/Shanghai");  
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");  
        TimeZone.setDefault(tz);  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");  
        String times = format.format(new Date(milliseconds));  
          
        return times;  
    }  
}